package com.zht.service.Impl;

import com.zht.model.Mail;
import com.zht.service.MailService;
import com.zht.util.ApiResponse;
import jakarta.annotation.Resource;
import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMailMessage;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;


@Service
@Slf4j
public class MailServiceImpl implements MailService {
    @Value("${spring.mail.username}")
    private String from;

    @Resource
    private JavaMailSender javaMailSender;

    @Override
    public ApiResponse sendSimpleMail(Mail mail) {

        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(mail.getTo());
        message.setSubject(mail.getSubject());
        message.setText(mail.getContent());
        try {
            javaMailSender.send(message);
            return ApiResponse.success("发送成功",mail.getContent());
        }catch (Exception e){
            return ApiResponse.error("发送失败");
        }


    }

    @Override
    public ApiResponse sendHTMLMail(Mail mail) {
        MimeMessage message = javaMailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
            helper.setFrom(from);
            helper.setTo(mail.getTo());
            helper.setSubject(mail.getSubject());
            helper.setText(mail.getContent(),true);

            javaMailSender.send(message);
            log.info("发送成功：收件人：{}",mail.getTo());
            return ApiResponse.success("发送成功",mail.getContent());

        } catch (MessagingException e) {
            return ApiResponse.error("发送失败");
        }
    }
}
